package com.wuhunyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.jwt.JwtUtils;
import com.wuhunyu.commonutils.jwt.MD5;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.entities.UcenterMember;
import com.wuhunyu.entities.vo.UserLogin;
import com.wuhunyu.entities.vo.UserRegister;
import com.wuhunyu.mapper.UcenterMemberMapper;
import com.wuhunyu.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhunyu.servicebase.exception.Assert;
import org.apache.ibatis.cache.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author wuhunyu
 * @since 2021-01-23
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Resource
    private UcenterMemberMapper ucenterMemberMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public CommonResult login(UserLogin userLogin) {
        // 校验参数
        Assert.isRight(Check.isBlank(userLogin), "用户登录对象为空");
        // 手机号
        Assert.isRight(Check.isBlank(userLogin.getEmail()), "邮箱不能为空");
        // 密码
        Assert.isRight(Check.isBlank(userLogin.getPassword()), "密码不能为空");
        // 根据手机号查询数据库
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userLogin.getEmail());
        List<UcenterMember> ucenterMembers = ucenterMemberMapper.selectList(queryWrapper);
        // 校验结果集
        Assert.isRight(ucenterMembers.size() != 1, "用户名不存在");
        // 判断用户是否被禁用
        Assert.isRight(ucenterMembers.get(0).getIsDeleted(), "用户已被禁用");
        // 校验密码
        Assert.isRight(!MD5.encrypt(userLogin.getEmail() + userLogin.getPassword()).equals(ucenterMembers.get(0).getPassword()), "密码错误");
        // 对数据进行封装
        String token = JwtUtils.getJwtToken(ucenterMembers.get(0).getId(), ucenterMembers.get(0).getNickname());
        Map<String, Object> map = new HashMap<>(16);
        map.put("token", token);
        return CommonResult.success("登录成功", map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult register(UserRegister userRegister) {
        // 校验参数
        Assert.isRight(Check.isBlank(userRegister), "用户注册对象不能为空");
        // 邮箱
        Assert.isRight(Check.isBlank(userRegister.getEmail()), "邮箱不能为空");
        // 昵称
        Assert.isRight(Check.isBlank(userRegister.getNickname()), "昵称不能为空");
        // 密码
        Assert.isRight(Check.isBlank(userRegister.getPassword()), "密码不能为空");
        // 验证码
        Assert.isRight(!(Check.isNotBlank(userRegister.getCode()) || userRegister.getCode().length() == 6), "验证码输入有误");
        // 结果集校验
        String code = redisTemplate.opsForValue().get(userRegister.getEmail());
        Assert.isRight(Check.isBlank(code), "未发送邮箱验证码");
        Assert.isRight(!code.equals(userRegister.getCode()), "邮箱验证码输入错误");
        // 邮箱不重复
        QueryWrapper<UcenterMember> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("email", userRegister.getEmail());
        List<UcenterMember> ucenterMembers = ucenterMemberMapper.selectList(queryWrapper1);
        System.out.println(ucenterMembers.size());
        System.out.println(Check.isNotBlank(ucenterMembers));
        Assert.isRight(!(ucenterMembers == null || ucenterMembers.size() == 0), "邮箱已注册");
        // 昵称不能重复
        QueryWrapper<UcenterMember> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("nickname", userRegister.getNickname());
        ucenterMembers = ucenterMemberMapper.selectList(queryWrapper2);
        Assert.isRight(!(ucenterMembers == null || ucenterMembers.size() == 0), "昵称已被占用");
        // 构造实体类
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setEmail(userRegister.getEmail());
        ucenterMember.setPassword(MD5.encrypt(userRegister.getEmail() + userRegister.getPassword()));
        ucenterMember.setNickname(userRegister.getNickname());
        ucenterMember.setIsDisabled(false);
        ucenterMember.setIsDeleted(false);
        // 执行添加用户操作
        Assert.isRight(ucenterMemberMapper.insert(ucenterMember) != 1, "用户注册失败");
        return CommonResult.success("用户注册成功");
    }

    @Override
    public CommonResult selectMemberInfo(HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        return this.selectMemberInfo(id);
    }

    @Override
    public CommonResult selectMemberInfo(String id) {
        // 校验参数
        Assert.isRight(Check.isBlank(id), "用户id异常，请重新登录");
        // 执行查询操作
        UcenterMember ucenterMember = ucenterMemberMapper.selectById(id);
        // 校验结果集
        Assert.isRight(Check.isBlank(ucenterMember), "用户不存在");
        // 封装结果集
        Map<String, Object> map = new HashMap<>(16);
        map.put("info", ucenterMember);
        return CommonResult.success("查询用户信息成功", map);
    }

    @Override
    public CommonResult countRegister(String date) {
        Assert.isRight(Check.isBlank(date), "日期不能为空");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        // 构造开始时间和结束时间
        Date start = null;
        Date end = null;
        try {
            start = dateFormat.parse(date + " 00:00:00");
            end = dateFormat.parse(date + " 23:59:59");
        } catch (ParseException e) {
            Assert.isRight(true, "时间转换失败");
        }
        Assert.isRight(Check.isBlank(start), "时间转换失败");
        Assert.isRight(Check.isBlank(end), "时间转换失败");
        // 执行
        Integer count = ucenterMemberMapper.countRegister(start, end);
        Assert.isRight(Check.isBlank(count), "注册人数统计失败");
        // 封装数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("register", count);
        return CommonResult.success("注册人数统计成功", map);
    }
}
